package edu.cque.sp02.controller;

import edu.cque.sp01.entity.Item;
import edu.cque.sp01.service.ItemService;
import edu.cque.sp01.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @author Hua
 * @create 2022-08-17 16:07
 */
@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    @GetMapping("/{orderId}")
    public JsonResult getItems(@PathVariable("orderId") String id) throws InterruptedException {
        // 延迟代码，90%概率执行延迟
        if (Math.random() < 0.9) {
            // 阻塞代码，随机 [0,5000)
            int t = new Random().nextInt(5000);
            log.info("阻塞时间： "+t);
            Thread.sleep(t);
        }

        return JsonResult.ok().data(itemService.getItems(id));
    }

    /*
    @Request 完整接收post 请求体中的数据
     */
    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(@RequestBody List<Item> items) {
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少库存成功");
    }

    @GetMapping("/favicon.ico")
    public void ico(){
        System.out.println("item: 浏览器访问的时候,会默认发送这个接口的请求,用来辨别网站返回的图标");

    }
}
